package com.lxp.tksys.filter;

import com.alibaba.fastjson.JSON;
import com.lxp.tksys.common.BaseContext;
import com.lxp.tksys.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")  //拦截全部,启动类中添加@ServletComponentScan
@Slf4j
public class LoginCheckFilter implements Filter {

    //AntPathMatcher路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        //需要放行的路径
        String[] urls = new String[]{
                "/employee/login",   //登录
                "/employee/logout",  //退出
                "/backend/**",       //页面展示
                "/front/**",
                "/user/sendMsg",   //用户发验证码、登录
                "/user/login",
                "/doc.html",     //swagger页面
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //调用check方法判断
        boolean check = check(urls, requestURI);   //以上路径直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //判断员工是否登录
        if (request.getSession().getAttribute("employee") != null) {  //有session(已登录)也放行
            log.info("用户已登录:{}", request.getSession().getAttribute("employee"));

            Long empId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);   //设置当前的操作人,后面可以取，实现公共字段填充

            long id=Thread.currentThread().getId();  //获取线程id->employeeControleer的update->MymetaHandler的insert/update
            log.info("线程id：{}",id);

            filterChain.doFilter(request, response);
            return;
        }

        //-----判断user是否登录
        if (request.getSession().getAttribute("user") != null) {  //有session(已登录)也放行
            log.info("用户已登录:{}", request.getSession().getAttribute("user"));

            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);   //设置当前的操作人,后面可以取，实现公共字段填充

            long id=Thread.currentThread().getId();  //获取线程id->employeeControleer的update->MymetaHandler的insert/update

            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


    }

    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {   //增强for循环进行匹配
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
